package com.lazyframework.security.web;

import com.lazyframework.security.web.configuration.properties.JsonWebTokenProperties;
import com.lazyframework.security.web.exception.JwtAuthenticationException;
import io.jsonwebtoken.*;

import java.io.Serializable;
import java.util.Base64;
import java.util.Date;

public class JwtClients {

    private final JsonWebTokenProperties jsonWebTokenProperties;

    public JwtClients(JsonWebTokenProperties jsonWebTokenProperties) {
        this.jsonWebTokenProperties = jsonWebTokenProperties;
    }

    /**
     * 生成token
     *
     * @param principal TOKEN中传递的主要内容（建议设置为用户ID）
     * @return TOKEN
     */
    public String encode(Serializable principal) {
        String base64EncodeKey = Base64.getEncoder()
                .encodeToString(jsonWebTokenProperties.secretKey().getBytes());
        return Jwts.builder()
                .setIssuer(jsonWebTokenProperties.issuer())
                .setIssuedAt(new Date())
                .claim("principal", principal)
                .setExpiration(new Date(System.currentTimeMillis() + (jsonWebTokenProperties.expire() * 1000)))
                .signWith(SignatureAlgorithm.HS256, base64EncodeKey)
                .compact();
    }

    /**
     * Token解码
     *
     * @param token TOKEN
     * @return 仅仅只返回存放在token中的主要信息principal
     * @throws JwtAuthenticationException
     */
    public String decode(String token) throws JwtAuthenticationException {
        Jwt jwt;
        String signKey = Base64.getEncoder().encodeToString(jsonWebTokenProperties.secretKey().getBytes());
        try {
            jwt = Jwts.parser().setSigningKey(signKey).parse(token);
        } catch (JwtException e) {
            throw new JwtAuthenticationException(e);
        }
        Claims claims = (Claims) jwt.getBody();
        return (String) claims.get("principal");
    }

}
